﻿using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace Brjnk.Common.UI
{
    public class ObjectPresenter : Control
    {
        private TreeView treeView;

        static ObjectPresenter()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(ObjectPresenter), new FrameworkPropertyMetadata(typeof(ObjectPresenter)));
        }

        public ObjectPresenter()
        {
            this.Loaded += new RoutedEventHandler(ObjectPresenter_Loaded);
        }

        private void ObjectPresenter_Loaded(object sender, RoutedEventArgs e)
        {
            treeView = this.GetTemplateChild("PART_TreeView") as TreeView;
            Update(Object);
        }

        public object Object
        {
            get { return (object)GetValue(ObjectProperty); }
            set { SetValue(ObjectProperty, value); }
        }

        public static readonly DependencyProperty ObjectProperty =
    DependencyProperty.Register("Object", typeof(object), typeof(ObjectPresenter), new UIPropertyMetadata(null, ObjectChanged));

        private static void ObjectChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            var target = sender as ObjectPresenter;
            if (target.treeView == null) return;
            target.Update(e.NewValue);
        }

        private void Update(object newValue)
        {
            if (newValue == null) treeView.DataContext = null;
            else treeView.DataContext = Enumerable.Repeat(new ObjectNode(newValue.GetType().ToString(), newValue), 1);
        }
    }
}